package com.xsd.xsdhouduan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xsd.xsdhouduan.entity.School;
import com.xsd.xsdhouduan.entity.Task;
import com.xsd.xsdhouduan.entity.User;
import com.xsd.xsdhouduan.mapper.TaskMapper;
import com.xsd.xsdhouduan.service.PlatformIncomeService;
import com.xsd.xsdhouduan.service.SchoolService;
import com.xsd.xsdhouduan.service.TaskService;
import com.xsd.xsdhouduan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * 任务服务实现类
 */
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {
    
    @Autowired
    private SchoolService schoolService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    @Lazy
    private PlatformIncomeService platformIncomeService;
    
    @Override
    @Transactional
    public boolean publishTask(Task task) {
        // 检查用户余额是否足够
        User publisher = userService.getById(task.getPublisherId());
        if (publisher == null) {
            return false;
        }
        
        BigDecimal taskReward = new BigDecimal(task.getReward().toString());
        if (publisher.getBalance() < taskReward.doubleValue()) {
            return false; // 余额不足
        }
        
        // 扣费：从用户余额中扣除任务奖励金额
        boolean deductSuccess = userService.updateBalance(task.getPublisherId(), -taskReward.doubleValue());
        if (!deductSuccess) {
            return false;
        }
        
        // 保存任务
        task.setStatus(0); // 待解决
        boolean saveSuccess = save(task);
        if (!saveSuccess) {
            // 如果保存失败，回滚余额
            userService.updateBalance(task.getPublisherId(), taskReward.doubleValue());
            return false;
        }
        
        // 记录平台收入（任务奖励转入管理账号）
        platformIncomeService.recordPublishFee(task.getId(), task.getPublisherId(), taskReward);
        
        // 记录平台费用（3%手续费）
        platformIncomeService.recordPlatformFee(task.getId(), task.getPublisherId(), taskReward);
        
        return true;
    }
    
    @Override
    public boolean acceptTask(Long taskId, Long accepterId) {
        Task task = getById(taskId);
        if (task != null && task.getStatus() == 0) {
            task.setAccepterId(accepterId);
            task.setStatus(2); // 解决中
            return updateById(task);
        }
        return false;
    }
    
    @Override
    @Transactional
    public boolean completeTask(Long taskId) {
        Task task = getById(taskId);
        if (task != null && task.getStatus() == 2) {
            task.setStatus(3); // 已完成
            task.setCompleteTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            boolean updateSuccess = updateById(task);
            
            if (updateSuccess) {
                // 记录任务完成费（97%的奖励给接取者）
                BigDecimal taskReward = new BigDecimal(task.getReward().toString());
                BigDecimal accepterAmount = taskReward.multiply(new BigDecimal("0.97")); // 97%给接取者
                platformIncomeService.recordCompleteFee(taskId, task.getAccepterId(), accepterAmount);
            }
            
            return updateSuccess;
        }
        return false;
    }
    
    @Override
    public boolean cancelTask(Long taskId) {
        Task task = getById(taskId);
        if (task != null && task.getStatus() == 2) {
            // 如果是解决中状态，取消后回到待解决状态，清空接受者
            task.setStatus(0); // 待解决
            task.setAccepterId(null); // 清空接受者
            return updateById(task);
        } else if (task != null && task.getStatus() == 0) {
            // 如果是待解决状态，取消后变为已关闭
            task.setStatus(1); // 已关闭
            return updateById(task);
        }
        return false;
    }
    
    @Override
    public boolean abandonTask(Long taskId) {
        Task task = getById(taskId);
        if (task != null && task.getStatus() == 2) {
            // 如果是解决中状态，放弃后回到待解决状态，清空接受者
            task.setStatus(0); // 待解决
            task.setAccepterId(null); // 清空接受者
            return updateById(task);
        }
        return false;
    }
    
    @Override
    public List<Task> getByPublisherId(Long publisherId) {
        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Task::getPublisherId, publisherId);
        List<Task> tasks = list(wrapper);
        return tasks.stream().map(this::populateTaskDetails).collect(java.util.stream.Collectors.toList());
    }
    
    @Override
    public List<Task> getByAccepterId(Long accepterId) {
        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Task::getAccepterId, accepterId);
        List<Task> tasks = list(wrapper);
        return tasks.stream().map(this::populateTaskDetails).collect(java.util.stream.Collectors.toList());
    }
    
    @Override
    public List<Task> getBySchoolId(Long schoolId) {
        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Task::getSchoolId, schoolId);
        List<Task> tasks = list(wrapper);
        return tasks.stream().map(this::populateTaskDetails).collect(java.util.stream.Collectors.toList());
    }
    
    @Override
    public Double getTotalRevenue() {
        List<Map<String, Object>> result = baseMapper.selectMaps(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Task>()
                .select("SUM(reward) as total")
        );
        
        if (result != null && !result.isEmpty()) {
            Object total = result.get(0).get("total");
            if (total != null) {
                return Double.valueOf(total.toString());
            }
        }
        return 0.0;
    }
    
    @Override
    public List<Task> getRecentTasks(int limit) {
        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Task::getCreateTime);
        wrapper.last("LIMIT " + limit);
        List<Task> tasks = list(wrapper);
        return tasks.stream().map(this::populateTaskDetails).collect(java.util.stream.Collectors.toList());
    }
    
    @Override
    public List<Task> getAllTasksWithDetails() {
        List<Task> tasks = list();
        return tasks.stream().map(this::populateTaskDetails).collect(java.util.stream.Collectors.toList());
    }
    
    /**
     * 填充任务详情（学校名称、接取者信息等）
     */
    private Task populateTaskDetails(Task task) {
        // 填充学校名称
        if (task.getSchoolId() != null) {
            School school = schoolService.getById(task.getSchoolId());
            if (school != null) {
                task.setSchoolName(school.getName());
            }
        }
        
        // 填充接取者信息
        if (task.getAccepterId() != null) {
            User accepter = userService.getById(task.getAccepterId());
            if (accepter != null) {
                task.setAccepterName(accepter.getName());
                task.setAccepterStudentId(accepter.getStudentId());
            }
        }
        
        return task;
    }
}
